package com.zzh.interview.filter;

import com.google.gson.Gson;
import com.zzh.interview.common.BaseResponse;
import com.zzh.interview.common.ResultUtils;
import com.zzh.interview.utils.BlackIpUtils;
import com.zzh.interview.utils.NetUtils;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.zzh.interview.common.ErrorCode.IP_BLACK;
import static com.zzh.interview.common.ErrorCode.LOGIN_CONFLICT;

// 黑名单IP过滤器 servlet原生 filter 优先级高于 springmvc 拦截器
@WebFilter(urlPatterns = "/*", filterName = "blackIpFilter")
@Order(1)
public class BlackIpFilter implements Filter {

    final Gson gson = new Gson();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        String ipAddress = NetUtils.getIpAddress((HttpServletRequest) servletRequest);
        System.out.println("访问IP地址：" + ipAddress);
        if (BlackIpUtils.isBlackIp(ipAddress)) {
            // 设置允许跨域的源
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
            // 允许携带凭证（如果需要）
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setContentType("text/json;charset=UTF-8");

            servletResponse.setContentType("text/json;charset=UTF-8");
            BaseResponse ipBlackResponse = ResultUtils.error(IP_BLACK);// 40800 登录冲突
            String json = gson.toJson(ipBlackResponse);
            response.getWriter().write(json);
//            servletResponse.getWriter().write("{\"code\":\"-1\",\"errorMsg\":\"黑名单IP，禁止访问\"}");
            // 不放行，直接返回json数据
            return;
        }
        //不是黑名单的IP正常放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
